package com.smalls.redshoes.util;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader.TileMode;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.text.TextUtils;
import android.util.LruCache;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BitmapUtils {
    private static final int maxMemory = ((int) Runtime.getRuntime().maxMemory());
    private static final int cacheSize = (maxMemory / 8);
    public static LruCache<String, Bitmap> mLruCache = new LruCache<String, Bitmap>(cacheSize) {
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getRowBytes() * bitmap.getHeight();
        }
    };

    public static ExecutorService pool = Executors.newFixedThreadPool(5);

    public interface BitmapCallBack {
        void load(Bitmap bitmap);
    }

    public interface HomeBitmapCallBack {
        void load(Bitmap bitmap, int i);
    }

    public static Bitmap createImageThumbnail(String filePath) {
        Bitmap bitmap = null;
        Options opts = new Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, opts);
        opts.inSampleSize = computeSampleSize(opts, -1, AccessibilityNodeInfoCompat.ACTION_COPY);
        opts.inJustDecodeBounds = false;
        try {
            bitmap = BitmapFactory.decodeFile(filePath, opts);
        } catch (Exception e) {
        }
        return bitmap;
    }

    public static int computeSampleSize(Options options, int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
        if (initialSize > 8) {
            return ((initialSize + 7) / 8) * 8;
        }
        int roundedSize = 1;
        while (roundedSize < initialSize) {
            roundedSize <<= 1;
        }
        return roundedSize;
    }

    private static int computeInitialSampleSize(Options options, int minSideLength, int maxNumOfPixels) {
        double w = (double) options.outWidth;
        double h = (double) options.outHeight;
        int lowerBound = maxNumOfPixels == -1 ? 1 : (int) Math.ceil(Math.sqrt((w * h) / ((double) maxNumOfPixels)));
        int upperBound = minSideLength == -1 ? 128 : (int) Math.min(Math.floor(w / ((double) minSideLength)), Math.floor(h / ((double) minSideLength)));
        if (upperBound < lowerBound) {
            return lowerBound;
        }
        if (maxNumOfPixels == -1 && minSideLength == -1) {
            return 1;
        }
        if (minSideLength != -1) {
            return upperBound;
        }
        return lowerBound;
    }

    public static void getHomeBitmap(final String urlStr, final int index, final int width, final int height, final HomeBitmapCallBack bitmapCallBack) {
        final Handler handler = new Handler() {
            public void handleMessage(Message message) {
                bitmapCallBack.load((Bitmap) message.obj, index);
            }
        };
        if (urlStr != null && !urlStr.equals("")) {
            new Thread(new Runnable() {
                public void run() {
                    String savePaht = BitmapUtils.mkdirs() + urlStr.substring(urlStr.lastIndexOf("/") + 1);
                    Bitmap bitmap = BitmapUtils.getLocalImage(savePaht, null, width, height);
                    if (bitmap == null) {
                        bitmap = BitmapUtils.createHttpBitmap(urlStr, width, height);
                        if (bitmap != null) {
                            BitmapUtils.saveFile(bitmap, savePaht);
                        }
                    }
                    if (bitmap != null) {
                        BitmapUtils.addBitmapToMemoryCache(urlStr, bitmap);
                        handler.obtainMessage(0, bitmap).sendToTarget();
                    }
                }
            }).start();
        }
    }

    public static void getBitmap(final String urlStr, final int width, final int height, final BitmapCallBack bitmapCallBack) {
        final Handler handler = new Handler() {
            public void handleMessage(Message message) {
                bitmapCallBack.load((Bitmap) message.obj);
            }
        };
        if (pool != null && !pool.isShutdown()) {
            pool.execute(new Thread(new Runnable() {
                public void run() {
                    Bitmap bitmap = BitmapUtils.createHttpBitmap(urlStr, width, height);
                    if (bitmap != null) {
                        BitmapUtils.addBitmapToMemoryCache(urlStr, bitmap);
                        handler.obtainMessage(0, bitmap).sendToTarget();
                    }
                }
            }));
        }
    }

    @SuppressLint({"NewApi"})
    private static void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (getBitmapFromMemoryCache(key) == null) {
            mLruCache.put(key, bitmap);
        }
    }

    @SuppressLint({"NewApi"})
    public static Bitmap getBitmapFromMemoryCache(String key) {
        return (Bitmap) mLruCache.get(key);
    }

    public static Options sampleSize(Options options, int w, int h) {
        options.inJustDecodeBounds = false;
        if (w <= 0 || h <= 0) {
            options.inSampleSize = 1;
        } else {
            int initialSize = Math.max((int) Math.ceil(Math.sqrt((double) ((options.outWidth * options.outHeight) / (w * h)))), Math.max(options.outWidth / w, options.outHeight / h));
            if (initialSize < 1) {
                options.inSampleSize = 1;
            } else {
                options.inSampleSize = initialSize;
            }
            if (initialSize < 1) {
                options.inSampleSize = 1;
            } else {
                options.inSampleSize = initialSize;
            }
        }
        return options;
    }

    public static Bitmap createHttpBitmap(String path, int target_w, int target_h) {
        OutOfMemoryError oor;
        IOException e;
        Options options = new Options();
        Bitmap dump = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
            conn.connect();
            is = conn.getInputStream();
            ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
            try {
                byte[] buffer = new byte[AccessibilityNodeInfoCompat.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY];
                while (true) {
                    int length = is.read(buffer);
                    if (length == -1) {
                        break;
                    } else if (options.mCancel) {
                        closeIO(is);
                        closeIO(baos2);
                        baos = baos2;
                        return null;
                    } else {
                        baos2.write(buffer, 0, length);
                    }
                }
                baos2.flush();
                byte[] data = baos2.toByteArray();
                options.inJustDecodeBounds = true;
                options.inSampleSize = 1;
                dump = BitmapFactory.decodeByteArray(data, 0, data.length, options);
                if (options.mCancel || options.outWidth == -1 || options.outHeight == -1) {
                    closeIO(is);
                    closeIO(baos2);
                    baos = baos2;
                    return null;
                }
                sampleSize(options, target_w, target_h);
                dump = BitmapFactory.decodeByteArray(data, 0, data.length, options);
                closeIO(is);
                closeIO(baos2);
                baos = baos2;
                return dump;
            } catch (OutOfMemoryError e2) {
                baos = baos2;
            } catch (IOException e3) {
                baos = baos2;
            } catch (Throwable th2) {
                baos = baos2;
            }
        } catch (OutOfMemoryError e4) {
            oor = e4;
            try {
                oor.printStackTrace();
                closeIO(is);
                closeIO(baos);
                return dump;
            } catch (Throwable th3) {
                closeIO(is);
                closeIO(baos);
            }
        } catch (IOException e5) {
            e = e5;
            e.printStackTrace();
            closeIO(is);
            closeIO(baos);
            return dump;
        }
        return dump;
    }

    public static Bitmap getLocalImage(String path, Options options, int target_w, int target_h) {
        Bitmap dump = null;
        if (new File(path).exists()) {
            if (options == null) {
                try {
                    options = new Options();
                } catch (OutOfMemoryError oom) {
                    oom.printStackTrace();
                }
            }
            options.inJustDecodeBounds = true;
            options.inSampleSize = 1;
            dump = BitmapFactory.decodeFile(path, options);
            if (options.mCancel || options.outWidth == -1 || options.outHeight == -1) {
                return null;
            }
            sampleSize(options, target_w, target_h);
            dump = BitmapFactory.decodeFile(path, options);
        }
        return dump;
    }

    public static void saveFile(Bitmap bm, String path) {
        IOException e;
        if (bm != null && !TextUtils.isEmpty(path)) {
            File file = new File(path);
            file.deleteOnExit();
            FileOutputStream fos = null;
            try {
                if (file.createNewFile()) {
                    FileOutputStream fos2 = new FileOutputStream(file);
                    try {
                        bm.compress(CompressFormat.PNG, 75, fos2);
                        fos2.flush();
                        fos = fos2;
                    } catch (IOException e2) {
                        e = e2;
                        fos = fos2;
                        try {
                            e.printStackTrace();
                            closeIO(fos);
                        } catch (Throwable th2) {
                            closeIO(fos);
                        }
                    } catch (Throwable th3) {
                        fos = fos2;
                        closeIO(fos);
                    }
                }
                closeIO(fos);
            } catch (IOException e3) {
                e = e3;
                e.printStackTrace();
                closeIO(fos);
            }
        }
    }

    public static String getAppDir() {
        return Environment.getExternalStorageDirectory().getAbsolutePath() + "/yuevod/img";
    }

    public static String mkdirs() {
        String path = getAppDir() + "/";
        File cache = new File(path);
        if (!cache.exists()) {
            cache.mkdirs();
        }
        return path;
    }

    public static void closeIO(Closeable io) {
        if (io != null) {
            try {
                io.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Bitmap createReflectedImages(Bitmap bm) {
        Bitmap bitmap = bm;
        Bitmap miniBitmap = Bitmap.createBitmap(bitmap, 0, 0, bm.getWidth(), bm.getHeight(), new Matrix(), true);
        int mwidth = miniBitmap.getWidth();
        int mheight = miniBitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.preScale(1.0f, -1.0f);
        Bitmap reflectionImage = Bitmap.createBitmap(miniBitmap, 0, mheight / 2, mwidth, mheight / 2, matrix, false);
        Bitmap bitmapWithReflection = Bitmap.createBitmap(mwidth, (int) (((float) mheight) * 1.2f), Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmapWithReflection);
        canvas.drawBitmap(miniBitmap, 0.0f, 0.0f, null);
        canvas.drawRect(0.0f, (float) mheight, (float) mwidth, (float) mheight, new Paint());
        canvas.drawBitmap(reflectionImage, 0.0f, (float) mheight, null);
        Paint paint = new Paint();
        paint.setShader(new LinearGradient(0.0f, (float) miniBitmap.getHeight(), 0.0f, (float) bitmapWithReflection.getHeight(), 1895825407, ViewCompat.MEASURED_SIZE_MASK, TileMode.CLAMP));
        paint.setAntiAlias(true);
        paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
        canvas.drawRect(0.0f, (float) mheight, (float) mwidth, (float) bitmapWithReflection.getHeight(), paint);
        return bitmapWithReflection;
    }

    public static void rotate3dAnimation(ImageView iv) {
        VodDeaitlPic rotation = new VodDeaitlPic(iv);
        rotation.setDuration(1000);
        rotation.setRepeatCount(1);
        rotation.setFillAfter(true);
        iv.startAnimation(rotation);
    }
}
